﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace iNet.Media.Imaging.Png
{
	#region PngChunk
	/// <summary>
	/// PNG Chunk。
	/// </summary>
	public struct PngChunk
	{
		#region 欄位
		public uint CRC;
		public byte[] Data;
		public int DataLength;
		public PngChunkType Type;
		#endregion
		#region 建構子
		/// <summary>
		/// 初始化 PngChunk 結構欄位。
		/// </summary>
		/// <param name="stream">提供資料的資料流。</param>
		public PngChunk(Stream stream)
		{
			//確認
			if (stream == null)
				throw new ArgumentNullException("stream");

			//取得長度及類型
			BitConverter converter = BitConverter.BigEndian;
			byte[] buffer = new byte[8];
			if (stream.Read(buffer, 0, 8) < 8)
				throw new EndOfStreamException();
			this.DataLength = converter.ToInt32(buffer, 0);
			this.Type = (PngChunkType)converter.ToUInt32(buffer, 4);

			//取得資料
			this.Data = new byte[this.DataLength];
			if (this.DataLength > 0 && stream.Read(this.Data, 0, this.DataLength) < this.DataLength)
				throw new EndOfStreamException();

			//取得 CRC
			if (stream.Read(buffer, 0, 4) < 4)
				throw new EndOfStreamException();
			this.CRC = converter.ToUInt32(buffer, 0);
		}
		#endregion
	}
	#endregion
	#region PngChunkType
	/// <summary>
	/// PNG Chunk 類型。
	/// </summary>
	public enum PngChunkType : uint
	{
		IHDR = 0x49484452,
		PLTE = 0x504C5445,
		IDAT = 0x49444154,
		IEND = 0x49454E44,
		bKGD = 0x624B4744,
		cHRM = 0x6348524D,
		gAMA = 0x67414D41,
		hIST = 0x68495354,
		iTXt = 0x69545874,
		pHYs = 0x70485973,
		sBIT = 0x73424954,
		tEXt = 0x74455874,
		tIME = 0x74494D45,
		tRNS = 0x74524E53,
		zTXt = 0x7A545874,
	}
	#endregion
}